package com.hepinghospital.user.base;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Debug;
import android.util.Log;

import androidx.multidex.MultiDexApplication;

import com.ainemo.sdk.otf.NemoSDK;
import com.ainemo.sdk.otf.NemoSDKInitCallBack;
import com.ainemo.sdk.otf.Settings;
import com.ainemo.sdk.otf.VideoConfig;
import com.kingja.loadsir.core.LoadSir;
import com.lky.toucheffectsmodule.TouchEffectsManager;
import com.lky.toucheffectsmodule.types.TouchEffectsViewType;
import com.lky.toucheffectsmodule.types.TouchEffectsWholeType;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
import com.hepinghospital.user.BuildConfig;
import com.hepinghospital.user.eventbus.WebSocket;
import com.hepinghospital.user.eventbus.WebSocketWrapper;
import com.hepinghospital.user.ui.activity.consult.ChatActivity;
import com.hepinghospital.user.ui.widget.EmptyCallback;
import com.hepinghospital.user.ui.widget.ErrorCallback;
import com.hepinghospital.user.ui.widget.LoadingCallback;
import com.hepinghospital.user.util.DebuggerUtils;
import com.rest.business.RestProxy;
import com.rest.response.Doctor;
import com.rest.response.MeetingResponse;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.ContextUtils;
import jz.joyoung.robot.util.LogUtil;
import jz.joyoung.robot.util.UIConstants;


/**
 * Created by Administrator on 2018/1/9.
 */

public class BaseApplication extends MultiDexApplication {

    public static String currentWXId = "";
    public static int userType; //1:基层医生 2：中心医院医生
    public static String currentUserId;
    public static String currentFamilyId;
    public static String name;
    public static String avatar;
    public static String sex;
    public static String doctorAvatar;
    public static String doctorSex;
    public static String mobile;
    public static String bookInfo;
    public static int diagnoseType = -1;
    public static String currentOrderId;
    public static Map<String, WebSocket> runningCalls = new HashMap<>();
    public static BaseApplication context;
    public static String diagnoseId = "";
    public static String doctorName;
    public static String jobTitleName;
    public static Doctor currentDoctor;

    public static boolean isPhoning;

    public static Boolean isXYLogin = false;
    public static String xyAccount = "";//小鱼账号
    public static String xyPassword = "";//小鱼账号密码

    public static Boolean isNursingPay = false;//是否是护理支付
    public static Boolean isNursiningList = false;//标志是从护理订单页跳转的

    private static final String FRONT_PKG = "com.qdsg.ysg.doctor";

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        ContextUtils.context = this;
        Logger.addLogAdapter(new AndroidLogAdapter());

//        detectedDynamicDebug();
        DebuggerUtils.checkDebuggableInNotDebugModel(context);
        LoadSir.beginBuilder()
                .addCallback(new ErrorCallback())//添加各种状态页
                .addCallback(new EmptyCallback())
                .addCallback(new LoadingCallback())
                .setDefaultCallback(LoadingCallback.class)//设置默认状态页
                .commit();
//        initXySDK();
    }

    /**
     * 小鱼sdk初始化
     */
    private void initXySDK() {
        Settings settings = new Settings("3e816492058911e7a31d000c29971af5");
        settings.setPrivateCloudAddress("39.172.69.238:7443");
        settings.setUiNeedSpeakers(true);
        settings.setVideoMaxResolutionTx(VideoConfig.VD_1280x720);
        settings.setDefaultCameraId(1);
        NemoSDK.getInstance().init(this, settings, new NemoSDKInitCallBack() {
            @Override
            public void nemoSdkInitSuccess() {
                LogUtil.e("小鱼SDK初始化成功");
            }

            @Override
            public void nemoSdkInitFail(String s, String s1) {
                LogUtil.e("SDK初始化失败");
            }
        });
    }


    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator((context, layout) -> {
//            layout.setPrimaryColorsId(android.R.color.white, R.color.mainGreen);//全局设置主题颜色
            return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator((context, layout) -> {
            //指定为经典Footer，默认是 BallPulseFooter
//            return new BallPulseFooter(context).setSpinnerStyle(SpinnerStyle.Scale);
            return new ClassicsFooter(context).setDrawableSize(20);
        });

        //设置全局使用哪种效果
        TouchEffectsManager.build(TouchEffectsWholeType.SCALE)
                //添加哪些View支持这个效果
                .addViewType(TouchEffectsViewType.ALL)
                //为父控件为列表的情况下，设置特定效果
                .setListWholeType(TouchEffectsWholeType.RIPPLE)
                //宽高比大于4时启动水波纹
                .setAspectRatioType(4f, TouchEffectsWholeType.RIPPLE);
    }

    public static Context getContext() {
        return context;
    }


    /**
     * 推送后，患者端加入会议
     *
     * @time 2020/11/26 15:17
     */
    private void getPushMeeting(String diagnoseId, String conferenceId, String conferenceNum, String phoneId, String meetingType, Context context) {
        RestProxy.getInstance().getPushMeeting(diagnoseId, conferenceId, conferenceNum, phoneId, meetingType, new Observer<MeetingResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(MeetingResponse meetingResponse) {
                Intent intentFour = new Intent(context, ChatActivity.class);
                WebSocketWrapper webSocketObj = new WebSocketWrapper();
                webSocketObj.diagnoseId = meetingResponse.diagnoseId;
                webSocketObj.conferenceID = meetingResponse.conferenceID;
                webSocketObj.passwdParticipant = meetingResponse.passwdParticipant;
                webSocketObj.meetingType = meetingResponse.meetingType;
                webSocketObj.token = meetingResponse.token;
                webSocketObj.conferenceNum = meetingResponse.conferenceNum;
                intentFour.putExtra("wsObj", webSocketObj);
                intentFour.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intentFour);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private static boolean isFrontProcess(Context context, String frontPkg) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

        assert manager != null;
        List<ActivityManager.RunningAppProcessInfo> infos = manager.getRunningAppProcesses();
        if (infos == null || infos.isEmpty()) {
            return false;
        }

        final int pid = android.os.Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : infos) {
            if (info.pid == pid) {
                Log.i(UIConstants.DEMO_TAG, "processName-->" + info.processName);
                return frontPkg.equals(info.processName);
            }
        }
        return false;
    }

    // 服务是否运行
    public boolean isServiceRunning(Context context, String serviceName) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        assert am != null;
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) am.getRunningServices(Integer.MAX_VALUE);


        for (ActivityManager.RunningServiceInfo info : runningService) {// 获取运行服务再启动
            if (info.service.getClassName().equals(serviceName)) {
                return true;
            }
        }
        return false;

    }

    /**
     * 检测动态调试
     */
    public void detectedDynamicDebug() {
        if (!BuildConfig.DEBUG) {
            if (Debug.isDebuggerConnected()) {
                //进程自杀
                int myPid = android.os.Process.myPid();
                android.os.Process.killProcess(myPid);

                //异常退出虚拟机
                System.exit(1);
            }
        }
    }
}

